import { KeywordModel} from "../../models/keyword.js";
import { BookModel  } from "../../models/book.js";
import { paginationBev } from "../behaviors/pagination.js";

const keyModel = new KeywordModel()
const bookModel  = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more:{
      type:String,
      observer:'LoadMore'//欧不瑟瑞
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    historyWords:[],
    hotWords:[],
    searching:false,
    q:'',
    loading:false,
    loadingCenter:false
  },
  attached(){//尔塔器的
    // let historyWords= keyModel.getHistory()
    // let hotWords = keyModel.getHot()
    this.setData({ historyWords: keyModel.getHistory()}) //历史搜索
    keyModel.getHot().then((res)=>{//热门搜索
      this.setData({hotWords: res.hot})
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onCancel(event){//取消触发事件
      this.initPagination()
      this.triggerEvent("cancel", {}, {})
    },
    onConfirm(event) {//监听输入框 存储缓存
      this._showResult()
      this._showLoadingCenter()
      const word = event.detail.value || event.detail.text
      this.setData({ q: word })
      bookModel.search(0, word).then((res)=>{
        this.setMoreData(res.books)
        this.setTotal(res.total)
        keyModel.addToHistory(word)//防止输入无意义的关键字
        this._hideLoadingCenter() 
      })
    },
    _showLoadingCenter(){//出入页面显示loading
      this.setData({
        loadingCenter:true
      })
    },
    _hideLoadingCenter() {//出入页面显示loading
      this.setData({
        loadingCenter: false
      })
    },
    _showResult(){//打开搜索内容面板
      this.setData({ searching: true })
    },
    _closeResult(){
      this.setData({ searching: false })
    },

    onDelete() {//点击查查图标
      this.initPagination()
      this.setData({ searching: false, q: "" })
    },
    LoadMore(){//触发下拉事件
      if(!this.data.q){return}
      if (this.isLocked()){return}
      if (this.hasMore()){
        this.locked()
        bookModel.search(this.getCurrentStart() , this.data.q).then((res) => {
          this.setMoreData(res.books)
          this.unlocked()
        },function(err) {
          this.unlocked()
          console.log("触发下拉事件LoadMore失败函数")
        }
        )
      }
    },
  }
  
})
